package misc

import (
	"encoding/json"

	"hub.hddznet.com/uniplatform/framework/logging"

	"github.com/gin-gonic/gin"
	"gopkg.in/mgo.v2/bson"
	"io/ioutil"
)

func ResultWithError(ctx *gin.Context, result interface{}, err error) {

	if err != nil {

		logging.Error(err.Error())

		ctx.JSON(200, bson.M{
			"Code":     9999,
			"Message":  err.Error(),
			"Response": nil,
		})

	} else {

		ctx.JSON(200, bson.M{
			"Code":     0,
			"Message":  "",
			"Response": result,
		})
	}
}

func Success(ctx *gin.Context, result interface{}) {
	ctx.JSON(200, bson.M{
		"Code":     0,
		"Message":  "",
		"Response": result,
	})
}

func Fail(ctx *gin.Context, message interface{}) {
	ctx.JSON(200, bson.M{
		"Code":     9999,
		"Message":  message,
		"Response": nil,
	})
}

func Grid(ctx *gin.Context, rows interface{}, count int64) {
	Success(ctx, bson.M{"total": count, "rows": rows})
}

//用于修改Bind,V不支持嵌套结构
func UBind(ctx *gin.Context, v interface{}) ([]string, error) {

	// bts := make([]byte, ctx.Request.ContentLength)
	// ctx.Request.Body.Read(bts)

	bts, err := ioutil.ReadAll(ctx.Request.Body)
	if err != nil {
		return nil, err
	}

	jobj := make(map[string]interface{})
	err = json.Unmarshal(bts, &jobj)
	if err != nil {
		return nil, err
	}
	err = json.Unmarshal(bts, v)
	if err != nil {
		return nil, err
	}

	fs := make([]string, 0)

	for k, _ := range jobj {
		fs = append(fs, k)
	}

	return fs, err
}
